import { DeleteResult } from 'mongoose';
import { ResourceModel } from '~/server/models/resource.model';

/**
 * @api {delete} /admin/resource/delete 删除资源
 * @apiName 删除资源
 * @apiGroup 资源管理
 * @apiDescription 删除资源，支持批量删除，多个权限 ID 使用英文逗号分隔
 *
 * @apiPermission admin、resource
 *
 * @apiSampleRequest /admin/resource/delete
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiQuery {String} id 资源 ID
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '成功删除 1 个资源',
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, ['admin', 'resource']);
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	const { id } = getQuery(event);

	if (!id || typeof id !== 'string') {
		return {
			code: 0,
			message: '参数错误',
		};
	}

	// 处理资源 ID，支持批量删除
	const ids: string[] = id.split(',');

	try {
		// 删除资源
		const deleteResult: DeleteResult = await ResourceModel.deleteMany({ _id: { $in: ids } });

		if (deleteResult.deletedCount < 1) {
			return {
				code: 0,
				message: '未找到要删除的资源',
			};
		}

		return {
			code: 1,
			message: `成功删除 ${deleteResult.deletedCount} 个资源`,
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
